package com.gking.centerSystem.config;

import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisPassword;
import org.springframework.data.redis.connection.RedisStandaloneConfiguration;
import org.springframework.data.redis.connection.lettuce.LettuceConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;


// RedisConfig.java
@Configuration
public class RedisConfig {

    @Value("${user-redis.host:localhost}")
    private String userRedisHost;

    @Value("${user-redis.port:6379}")
    private int userRedisPort;

    @Value("${user-redis.password:}")  // 默认为空字符串
    private String userRedisPassword;

    @Value("${user-redis.database:1}")
    private int userRedisDatabase;

    @Value("${user-redis.timeout:2000}")
    private long userRedisTimeout;

    
    private RedisTemplate<String, Object> createRedisTemplate(RedisConnectionFactory connectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.afterPropertiesSet();
        return template;
    }


    @Bean(name = "userRedisTemplate")
    public RedisTemplate<String, Object> userRedisTemplate(
            @Qualifier("userRedisConnectionFactory") RedisConnectionFactory connectionFactory) {
        return createRedisTemplate(connectionFactory);
    }


    @Bean(name = "userRedisConnectionFactory")
    public RedisConnectionFactory userRedisConnectionFactory() {
        RedisStandaloneConfiguration config = new RedisStandaloneConfiguration(userRedisHost, userRedisPort);
        // 设置数据库
        config.setDatabase(userRedisDatabase);
        // 设置密码（使用新 API）
        if (userRedisPassword != null) config.setPassword(RedisPassword.of(userRedisPassword));

        LettuceConnectionFactory factory = new LettuceConnectionFactory(config);
        factory.setTimeout(userRedisTimeout);

        return factory;
    }

}